<?php
/**
 * QrCode.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-14 02:04:21
 * @modified    2023-02-14 02:04:21
 *
 */

namespace App\Models\Product;

use App\Models\BaseModel;
use App\Models\Product;
use Carbon\Carbon;

class QrCode extends BaseModel
{
    protected $table = 'product_qrcode';

    protected $fillable = [
        'product_id',
        'create_user_id',
        'path',
        'code'
    ];

    protected $appends = ['url', 'status_code', 'status_title', 'create_time_format', 'update_time_format'];

    public function scopeByProductId($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function scopeByCode($query, $code)
    {
        return $query->where('code', $code);
    }

    public function scopeByIds($query, $ids)
    {
        return $query->whereIn('id', $ids);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function getUrlAttribute()
    {
        return trim(env('APP_URL'), '/') . '/' . $this->path;
    }

    public function getStatusCodeAttribute()
    {
        $productId = $this->product_id;
        if ($productId) {
            return 'associated';
        }
        return 'un_associated';
    }

    public function getStatusTitleAttribute()
    {
        $productId = $this->product_id;
        if ($productId) {
            return '已关联';
        }
        return '未关联';
    }

    public function getCreateTimeFormatAttribute()
    {
        return Carbon::parse($this->create_time)->toDateTimeString();
    }

    public function getUpdateTimeFormatAttribute()
    {
        return Carbon::parse($this->update_time)->toDateTimeString();
    }
}